package cn.thoughtworks.school.pactise.diary.domain.context.practiseDiaryContext.practiseDiary;

import org.springframework.stereotype.Service;

import javax.persistence.Tuple;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PractiseDiaryService  {

    final PractiseDiaryRepository practiseDiaryRepository;

    public PractiseDiaryService(PractiseDiaryRepository practiseDiaryRepository) {
        this.practiseDiaryRepository = practiseDiaryRepository;
    }

    public List<PractiseDiary> findMonthlyDiariesByAuthorId(Long authorId, int year, int month) {

        Calendar startDate = getCalendar(year, month);
        Calendar endDate = getCalendar(year, month);
        endDate.add(Calendar.MONTH, 1);

        return practiseDiaryRepository.findByAuthorIdAndDateBetween(authorId, startDate.getTime(), endDate.getTime());

    }

    private Calendar getCalendar(int year, int month) {
        Calendar date = Calendar.getInstance();
        date.set(year, month, 1);
        return date;
    }

    public List<PractiseDiaryCount> findYearSubmitCountByAuthorId(Long authorId, int year) {

        Calendar startDate = getCalendar(year, 1);
        Calendar endDate = getCalendar(year + 1, 1);
        final List<Tuple> monthlyCount = practiseDiaryRepository.getMonthlyCountByAuthorIdAndYearBetween(authorId, startDate.getTime(), endDate.getTime());
        return monthlyCount.stream()
            .map(tuple -> {
                int month = tuple.get("month", Integer.class);
                long count = tuple.get("count", BigInteger.class).longValue();
                return (new PractiseDiaryCount(month, count));
            }).collect(Collectors.toList());
    }

    public PractiseDiary save(PractiseDiary practiseDiary) {
        return practiseDiaryRepository.save(practiseDiary);
    }

    public void delete(long id) {
        practiseDiaryRepository.deleteById(id);
    }
}
